package com.suning.sawp.in.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.common.EmployeeInfo;
import com.suning.sawp.in.filter.RequestUserHolder;
import com.suning.sawp.intf.mainpush.MainPushService;
import com.suning.sawp.intf.mainpush.OperationLogService;
import com.suning.sawp.intf.task.RegionHandlerService;
import com.suning.sawp.po.mainpush.StoreCommodityTask;
import com.suning.sawp.po.mainpush.TaskRegion;
import com.suning.sawp.service.util.GsonUtils;

/**
 * 〈主推任务后台控制类〉<br>
 * 〈功能详细描述〉
 *
 * @author 12061748
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/adminPage/mainPush")
public class MainPushBackController extends DjBaseController {
    private static final String ERROR_MESSAGE = "errorMessage";

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);

    private static final int MAX_SIZE_4096 = 4096;

    private static final String RET_FLAG = "retFlag";

    private static final String FAIL = "0";

    private static final String SUCCESS = "1";

    @Autowired
    MainPushService mainPushService;

    @Autowired
    RegionHandlerService regionHandlerService;

    @Autowired
    OperationLogService operationLogService;

    /**
     * 
     * 功能描述:查询大区任务列表 <br>
     * 〈功能详细描述〉
     *
     * @param orgLevel
     * @param taskTopic
     * @param startTime
     * @param endTime
     * @param pageNo
     * @param pageLimit
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryRegionTaskList.do")
    @ResponseBody
    public String queryRegionTaskList(String taskTopic, String startTime, String endTime, Integer pageNo,
            Integer pageLimit) {
        EmployeeInfo requestUser = RequestUserHolder.getRequestUser();
        // 检验是否是大区对接人，是则返回大区编码
        String regionCode = regionHandlerService.queryRegionHandlerByStaffCode(requestUser.getStaffId());
        if (StringUtils.isBlank(regionCode)) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put(RET_FLAG, FAIL);
            map.put(ERROR_MESSAGE, "非大区对接人");
            return GsonUtils.toJson(map, false);
        }
        // 查询大区分公司列表
        Map<String, Object> result = mainPushService.queryRegionMainPushList(regionCode, taskTopic, startTime, endTime,
                (pageNo - 1) * pageLimit, pageLimit);
        return GsonUtils.toJson(result, false);
    }

    /**
     * 
     * 功能描述: 查询大区某一条任务的详情<br>
     * 〈功能详细描述〉
     *
     * @param taskNo
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryRegionTaskDetail.do")
    @ResponseBody
    public String queryRegionTaskDetail(String taskNo) {
        Map<String, Object> result = new HashMap<String, Object>();
        // 查询大区分公司列表
        TaskRegion task = mainPushService.queryRegionTaskDetail(taskNo);
        task = mainPushService.queryRegionCommDestSum(task);
        result.put("data", task);
        result.put(RET_FLAG, SUCCESS);
        return GsonUtils.toJson(result, false);
    }

    /**
     * 
     * 功能描述: 查询大区商品任务列表<br>
     * 〈功能详细描述〉
     *
     * @param taskNo
     * @param regionCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryRegionTaskCommList.do")
    @ResponseBody
    public String queryRegionTaskCommList(String taskNo, Integer pageNo, Integer pageLimit) {
        Map<String, Object> result = mainPushService.queryRegionTaskCommList(taskNo, (pageNo - 1) * pageLimit,
                pageLimit);
        return GsonUtils.toJson(result, false);
    }

    /**
     * 
     * 功能描述:查询大区下面各个门店的分配数量 <br>
     * 〈功能详细描述〉
     *
     * @param taskNo
     * @param commClassifyCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryStoreDestNum.do")
    @ResponseBody
    public String queryStoreDestNum(String taskNo, String commClassifyCode) {
        Map<String, Object> result = mainPushService.queryStoreTaskCommList(taskNo, commClassifyCode);
        return GsonUtils.toJson(result, false);
    }

    /**
     * 
     * 功能描述:修改大区下面各个门店的分配数量<br>
     * 〈功能详细描述〉
     *
     * @param task
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/upsertStoreDestNum.do")
    @ResponseBody
    public String upsertStoreDestNum(String commList, String taskNo, String commClassifyCode) {
        EmployeeInfo requestUser = RequestUserHolder.getRequestUser();
        List<StoreCommodityTask> list = null;
        try {
            list = new Gson().fromJson(commList, new TypeToken<List<StoreCommodityTask>>() {
            }.getType());
        } catch (JsonSyntaxException e) {
            LOGGER.error("数据结构错误", e);
        }
        Map<String, Object> map = mainPushService.upsertStoreCommTask(taskNo, commClassifyCode, list,
                requestUser.getStaffId());
        return GsonUtils.toJson(map);
    }

    /**
     * 
     * 功能描述:导出大区的各个门店的各个商品的分配个数 <br>
     * 〈功能详细描述〉
     *
     * @param regionCode
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/storeAssignExport.do")
    public void storeAssignExport(String taskNo, HttpServletResponse response) {
        EmployeeInfo requestUser = RequestUserHolder.getRequestUser();
        // 检验是否是大区对接人，是则返回大区编码
        String regionCode = regionHandlerService.queryRegionHandlerByStaffCode(requestUser.getStaffId());
        InputStream is = null;
        OutputStream os = null;
        File file = null;
        try {
            file = mainPushService.storeAssignExport(regionCode, taskNo);
            is = new FileInputStream(file.getPath());
            os = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + new String("各门店任务分配模板.xls".getBytes("UTF-8"), "ISO8859-1"));
            byte[] buffer = new byte[MAX_SIZE_4096];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            LOGGER.error("各门店任务分配模板错误", e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error("关闭os流失败", e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("关闭is流失败", e);
                }
            }
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    LOGGER.error("删除文件失败");
                }
            }
        }
    }

    /**
     * 
     * 功能描述:导入大区的各个门店的各个商品的分配个数 <br>
     * 〈功能详细描述〉
     *
     * @param taskNo
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/storeAssignImport.do")
    @ResponseBody
    public String storeAssignImport(@RequestParam(value = "upfile", required = true) MultipartFile file, String taskNo) {
        Map<String, Object> result = new HashMap<String, Object>();
        EmployeeInfo requestUser = RequestUserHolder.getRequestUser();
        // 检验是否是大区对接人，是则返回大区编码
        String regionCode = regionHandlerService.queryRegionHandlerByStaffCode(requestUser.getStaffId());
        if (StringUtils.isEmpty(regionCode)) {
            result.put(RET_FLAG, FAIL);
            result.put(ERROR_MESSAGE, "非大区对接人");
            return GsonUtils.toJson(result, false);
        }
        // 创建对Excel工作簿文件的引用
        Workbook wookbook = null;
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());

        try {
            if ("xls".equals(fileType)) {
                wookbook = new HSSFWorkbook(file.getInputStream());
            } else if ("xlsx".equals(fileType)) {
                wookbook = new XSSFWorkbook(file.getInputStream());
            } else {
                result.put(RET_FLAG, FAIL);
                result.put(ERROR_MESSAGE, "文件格式错误");
                return GsonUtils.toJson(result, false);
            }
        } catch (Exception e) {
            LOGGER.error("解析excel出错", e);
            result.put(RET_FLAG, FAIL);
            result.put(ERROR_MESSAGE, "文件格式错误");
            return GsonUtils.toJson(result, false);
        }
        // 默认取第一个sheet
        Sheet sheet = wookbook.getSheetAt(0);
        try {
            result = mainPushService.storeAssignImport(sheet, taskNo, regionCode);
        } catch (Exception e) {
            LOGGER.error("解析excel出错", e);
            result.put(RET_FLAG, FAIL);
            result.put(ERROR_MESSAGE, "文件非导出模板，请重新选择");
        }
        return GsonUtils.toJson(result, false);
    }

    /**
     * 
     * 功能描述: 查询操作日志<br>
     * 〈功能详细描述〉
     *
     * @param taskNo
     * @param startTime
     * @param endTime
     * @param pageNo
     * @param pageLimit
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/queryOptLog.do")
    @ResponseBody
    public String queryOptLog(String taskNo, String startTime, String endTime, Integer pageNo, Integer pageLimit) {
        // 查询大区分公司列表
        Map<String, Object> result = mainPushService.queryOperationLog(taskNo, startTime, endTime, (pageNo - 1)
                * pageLimit, pageLimit);
        return GsonUtils.toJson(result, false);
    }

    /**
     * 
     * 功能描述:导出各门店完成情况 <br>
     * 〈功能详细描述〉
     *
     * @param taskNo
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/regionExportCompltInfo.do")
    public void regionExportCompltInfo(String taskNos, HttpServletResponse response) {
        List<String> list = null;
        try {
            list = new Gson().fromJson(taskNos, new TypeToken<List<String>>() {
            }.getType());
        } catch (JsonSyntaxException e) {
            LOGGER.error("数据结构错误", e);
        }
        InputStream is = null;
        OutputStream os = null;
        File file = null;
        try {
            file = mainPushService.exportCompltInfo(list, false);
            is = new FileInputStream(file.getPath());
            os = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + new String("各门店主推任务完成情况.xls".getBytes("UTF-8"), "ISO8859-1"));
            byte[] buffer = new byte[MAX_SIZE_4096];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            LOGGER.error("各门店任务分配模板错误", e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error("关闭os流失败", e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("关闭is流失败", e);
                }
            }
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    LOGGER.error("删除文件失败");
                }
            }
        }
    }

    /**
     * 
     * 功能描述:导出各大区完成情况 <br>
     * 〈功能详细描述〉
     *
     * @param taskNo
     * @param response
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    @RequestMapping("/hqExportCompltInfo.do")
    public void hqExportCompltInfo(String taskNos, HttpServletResponse response) {
        List<String> list = null;
        try {
            list = new Gson().fromJson(taskNos, new TypeToken<List<String>>() {
            }.getType());
        } catch (JsonSyntaxException e) {
            LOGGER.error("数据结构错误", e);
        }
        InputStream is = null;
        OutputStream os = null;
        File file = null;
        try {
            file = mainPushService.exportCompltInfo(list, true);
            is = new FileInputStream(file.getPath());
            os = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + new String("各大区主推任务完成情况.xls".getBytes("UTF-8"), "ISO8859-1"));
            byte[] buffer = new byte[MAX_SIZE_4096];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            LOGGER.error("各大区任务分配模板错误", e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error("关闭os流失败", e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("关闭is流失败", e);
                }
            }
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    LOGGER.error("删除文件失败");
                }
            }
        }
    }
}
